using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.IO;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 写作进度服务
    /// </summary>
    public class WritingProgressService
    {
        private readonly ILogger<WritingProgressService> _logger;
        private readonly IDataStorageService _dataStorage;

        public WritingProgressService(
            ILogger<WritingProgressService> logger,
            IDataStorageService dataStorage)
        {
            _logger = logger;
            _dataStorage = dataStorage;
        }

        /// <summary>
        /// 更新小说项目进度
        /// </summary>
        public async Task UpdateNovelProjectProgressAsync(int novelProjectId, int currentChapter, int totalWordCount)
        {
            try
            {
                var novelProject = await _dataStorage.GetNovelProjectAsync(novelProjectId);
                if (novelProject == null)
                {
                    throw new InvalidOperationException($"小说项目不存在: {novelProjectId}");
                }

                novelProject.CurrentChapterCount = currentChapter;
                novelProject.TotalWordCount = totalWordCount;
                novelProject.LastWritingTime = DateTime.Now;
                novelProject.UpdatedAt = DateTime.Now;

                // 根据进度更新状态
                if (currentChapter > 0)
                {
                    novelProject.Status = "Writing";
                }

                if (currentChapter >= novelProject.TargetChapterCount)
                {
                    novelProject.Status = "Completed";
                }

                await _dataStorage.UpdateNovelProjectAsync(novelProject);

                _logger.LogInformation($"小说项目进度已更新: 项目ID={novelProjectId}, 当前章节={currentChapter}, 总字数={totalWordCount}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新小说项目进度失败: 项目ID={novelProjectId}");
                throw;
            }
        }

        /// <summary>
        /// 更新章节进度
        /// </summary>
        public async Task UpdateChapterProgressAsync(int chapterId, string status, int wordCount)
        {
            try
            {
                var chapter = await _dataStorage.GetChapterAsync(chapterId);
                if (chapter == null)
                {
                    throw new InvalidOperationException($"章节不存在: {chapterId}");
                }

                chapter.Status = status;
                chapter.WordCount = wordCount;
                chapter.UpdatedAt = DateTime.Now;

                if (status == "Writing" && chapter.StartedAt == null)
                {
                    chapter.StartedAt = DateTime.Now;
                }

                if (status == "Completed")
                {
                    chapter.CompletedAt = DateTime.Now;
                }

                await _dataStorage.UpdateChapterAsync(chapter);

                _logger.LogInformation($"章节进度已更新: 章节ID={chapterId}, 状态={status}, 字数={wordCount}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新章节进度失败: 章节ID={chapterId}");
                throw;
            }
        }

        /// <summary>
        /// 保存章节内容到项目文件夹
        /// </summary>
        public async Task SaveChapterToProjectAsync(int chapterId, string content, string projectPath, string bookTitle)
        {
            try
            {
                var chapter = await _dataStorage.GetChapterAsync(chapterId);
                if (chapter == null)
                {
                    throw new InvalidOperationException($"章节不存在: {chapterId}");
                }

                // 创建章节文件夹
                var chaptersPath = Path.Combine(projectPath, "章节");
                if (!Directory.Exists(chaptersPath))
                {
                    Directory.CreateDirectory(chaptersPath);
                }

                // 生成文件名：书籍名称_卷宗号_卷宗名称_章节号_章节名称.docx
                var volumeNumber = CalculateVolumeNumber(chapter.ChapterNumber);
                var volumeName = $"第{volumeNumber}卷";
                var fileName = $"{bookTitle}_{volumeNumber:D2}_{volumeName}_{chapter.ChapterNumber:D3}_{chapter.Title}.docx";
                var filePath = Path.Combine(chaptersPath, fileName);

                // 保存为Word文档
                await SaveAsWordDocumentAsync(content, filePath);

                // 更新章节的文档路径
                chapter.ContentPath = filePath;
                await _dataStorage.UpdateChapterAsync(chapter);

                _logger.LogInformation($"章节已保存到项目文件夹: {filePath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存章节到项目文件夹失败: 章节ID={chapterId}");
                throw;
            }
        }

        /// <summary>
        /// 保存大纲到项目文件夹
        /// </summary>
        public async Task SaveOutlineToProjectAsync(string outline, string projectPath, string fileName)
        {
            try
            {
                var outlinesPath = Path.Combine(projectPath, "大纲");
                if (!Directory.Exists(outlinesPath))
                {
                    Directory.CreateDirectory(outlinesPath);
                }

                var filePath = Path.Combine(outlinesPath, $"{fileName}.txt");
                await File.WriteAllTextAsync(filePath, outline);

                _logger.LogInformation($"大纲已保存到项目文件夹: {filePath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存大纲到项目文件夹失败: {fileName}");
                throw;
            }
        }

        /// <summary>
        /// 保存世界设定到项目文件夹
        /// </summary>
        public async Task SaveWorldSettingToProjectAsync(WorldSetting worldSetting, string projectPath)
        {
            try
            {
                var settingsPath = Path.Combine(projectPath, "设定");
                if (!Directory.Exists(settingsPath))
                {
                    Directory.CreateDirectory(settingsPath);
                }

                var filePath = Path.Combine(settingsPath, "世界设定.json");
                var json = JsonConvert.SerializeObject(worldSetting, Formatting.Indented);
                await File.WriteAllTextAsync(filePath, json);

                _logger.LogInformation($"世界设定已保存到项目文件夹: {filePath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存世界设定到项目文件夹失败");
                throw;
            }
        }

        /// <summary>
        /// 更新文档编辑器内容
        /// </summary>
        public event Action<string>? DocumentEditorContentUpdated;

        /// <summary>
        /// 通知文档编辑器更新内容
        /// </summary>
        public void NotifyDocumentEditorUpdate(string content)
        {
            DocumentEditorContentUpdated?.Invoke(content);
        }

        /// <summary>
        /// 获取项目创作统计信息
        /// </summary>
        public async Task<WritingStatistics> GetWritingStatisticsAsync(int novelProjectId)
        {
            try
            {
                var novelProject = await _dataStorage.GetNovelProjectAsync(novelProjectId);
                if (novelProject == null)
                {
                    throw new InvalidOperationException($"小说项目不存在: {novelProjectId}");
                }

                var chapters = await _dataStorage.GetChaptersAsync(novelProjectId);
                
                var statistics = new WritingStatistics
                {
                    NovelProjectId = novelProjectId,
                    BookTitle = novelProject.Title,
                    TotalChapters = novelProject.TargetChapterCount,
                    CompletedChapters = chapters.Count(c => c.Status == "Completed"),
                    TotalWordCount = novelProject.TotalWordCount,
                    AverageWordsPerChapter = chapters.Count > 0 ? chapters.Average(c => c.WordCount) : 0,
                    CreatedAt = novelProject.CreatedAt,
                    LastWritingTime = novelProject.LastWritingTime,
                    Status = novelProject.Status
                };

                // 计算预计完成时间
                if (statistics.CompletedChapters > 0 && novelProject.LastWritingTime.HasValue)
                {
                    var timeSpan = novelProject.LastWritingTime.Value - novelProject.CreatedAt;
                    var averageTimePerChapter = timeSpan.TotalDays / statistics.CompletedChapters;
                    var remainingChapters = statistics.TotalChapters - statistics.CompletedChapters;
                    statistics.EstimatedCompletionDate = DateTime.Now.AddDays(remainingChapters * averageTimePerChapter);
                }

                return statistics;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取创作统计信息失败: 项目ID={novelProjectId}");
                throw;
            }
        }

        /// <summary>
        /// 计算卷宗号（每50章为一卷）
        /// </summary>
        private int CalculateVolumeNumber(int chapterNumber)
        {
            return (chapterNumber - 1) / 50 + 1;
        }

        /// <summary>
        /// 保存为Word文档
        /// </summary>
        private async Task SaveAsWordDocumentAsync(string content, string filePath)
        {
            try
            {
                // 这里需要实现Word文档保存功能
                // 可以使用DocumentFormat.OpenXml或其他库
                // 暂时保存为文本文件
                await File.WriteAllTextAsync(filePath.Replace(".docx", ".txt"), content);
                
                _logger.LogInformation($"内容已保存为文本文件: {filePath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存Word文档失败: {filePath}");
                throw;
            }
        }
    }

    /// <summary>
    /// 创作统计信息
    /// </summary>
    public class WritingStatistics
    {
        /// <summary>
        /// 小说项目ID
        /// </summary>
        public int NovelProjectId { get; set; }

        /// <summary>
        /// 书籍标题
        /// </summary>
        public string BookTitle { get; set; } = string.Empty;

        /// <summary>
        /// 目标章节数
        /// </summary>
        public int TotalChapters { get; set; }

        /// <summary>
        /// 已完成章节数
        /// </summary>
        public int CompletedChapters { get; set; }

        /// <summary>
        /// 总字数
        /// </summary>
        public int TotalWordCount { get; set; }

        /// <summary>
        /// 平均每章字数
        /// </summary>
        public double AverageWordsPerChapter { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedAt { get; set; }

        /// <summary>
        /// 最后写作时间
        /// </summary>
        public DateTime? LastWritingTime { get; set; }

        /// <summary>
        /// 项目状态
        /// </summary>
        public string Status { get; set; } = string.Empty;

        /// <summary>
        /// 预计完成时间
        /// </summary>
        public DateTime? EstimatedCompletionDate { get; set; }

        /// <summary>
        /// 完成进度百分比
        /// </summary>
        public double ProgressPercentage => TotalChapters > 0 ? (double)CompletedChapters / TotalChapters * 100 : 0;
    }
}
